package com.yiwei.jmx.activity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.star.lockpattern.util.LockPatternUtil;
import com.star.lockpattern.widget.LockPatternIndicator;
import com.star.lockpattern.widget.LockPatternView;
import com.yiwei.jmx.R;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.util.ACache;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.EnableScrollView;
import com.yiwei.jmx.view.SelectMenuTipsDilaog;
import com.yiwei.jmx.view.V19FrameLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * create gesture activity
 * Created by Sym on 2015/12/23.
 */
public class CreateGestureActivity extends BaseActivity {

    @BindView(R.id.lockPatterIndicator)
    LockPatternIndicator lockPatternIndicator;
    @BindView(R.id.lockPatternView)
    LockPatternView lockPatternView;
    @BindView(R.id.resetBtn)
    Button resetBtn;
    @BindView(R.id.messageTv)
    TextView messageTv;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.txt_username)
    TextView txtUsername;
    @BindView(R.id.scrollView)
    EnableScrollView scrollView;
    private boolean is_check;
    private List<LockPatternView.Cell> mChosenPattern = null;
    private ACache aCache;
    private static final long DELAYTIME = 600L;
    private static final String TAG = "CreateGestureActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_gesture);
        initBar();
        ButterKnife.bind(this);
        this.init();
    }

    private void init() {
        txtTitle.setText("设置手势密码");
        is_check = getIntent().getBooleanExtra("is_check", false);
        aCache = ACache.get(CreateGestureActivity.this);
        lockPatternView.setOnPatternListener(patternListener);
        setIsNeedCheckLogout(false);
        Glide.with(this).load(UserInfoGlobal.getHeader()).dontAnimate().placeholder(R.mipmap.img_guesture_default_icon).error(R.mipmap.img_guesture_default_icon).into(imgIcon);
//        txtUsername.setText(Util.replaceString(UserInfoGlobal.getMobile(), 5, 4, '*'));
    }

    /**
     * 手势监听
     */
    private LockPatternView.OnPatternListener patternListener = new LockPatternView.OnPatternListener() {

        @Override
        public void onPatternStart() {
            scrollView.setSetTouchMode(false);
            lockPatternView.removePostClearPatternRunnable();
            //updateStatus(Status.DEFAULT, null);
            lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
        }

        @Override
        public void onPatternComplete(List<LockPatternView.Cell> pattern) {
            scrollView.setSetTouchMode(true);
            //Log.e(TAG, "--onPatternDetected--");
            if (mChosenPattern == null && pattern.size() >= 4) {
                mChosenPattern = new ArrayList<LockPatternView.Cell>(pattern);
                updateStatus(Status.CORRECT, pattern);
            } else if (mChosenPattern == null && pattern.size() < 4) {
                updateStatus(Status.LESSERROR, pattern);
            } else if (mChosenPattern != null) {
                if (mChosenPattern.equals(pattern)) {
                    updateStatus(Status.CONFIRMCORRECT, pattern);
                } else {
                    updateStatus(Status.CONFIRMERROR, pattern);
                }
            }
        }
    };

    /**
     * 更新状态
     *
     * @param status
     * @param pattern
     */
    private void updateStatus(Status status, List<LockPatternView.Cell> pattern) {
        messageTv.setTextColor(getResources().getColor(status.colorId));
        messageTv.setText(status.strId);
        switch (status) {
            case DEFAULT:
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                break;
            case CORRECT:
                updateLockPatternIndicator();
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                break;
            case LESSERROR:
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                break;
            case CONFIRMERROR:
                lockPatternView.setPattern(LockPatternView.DisplayMode.ERROR);
                lockPatternView.postClearPatternRunnable(DELAYTIME);
                break;
            case CONFIRMCORRECT:
                saveChosenPattern(pattern);
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                setLockPatternSuccess();
                break;
        }
    }

    /**
     * 更新 Indicator
     */
    private void updateLockPatternIndicator() {
        if (mChosenPattern == null)
            return;
        lockPatternIndicator.setIndicator(mChosenPattern);
    }

    /**
     * 重新设置手势
     */
    @OnClick(R.id.resetBtn)
    void resetLockPattern() {
        mChosenPattern = null;
        lockPatternIndicator.setDefaultIndicator();
        updateStatus(Status.DEFAULT, null);
        lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
    }


    /**
     * 保存手势密码
     */
    private void saveChosenPattern(List<LockPatternView.Cell> cells) {
        byte[] bytes = LockPatternUtil.patternToHash(cells);
        //        通过修改不同的key，有很多个手势密码
        aCache.put(Const.GESTURE_PASSWORD, bytes);
    }

    /**
     * 成功设置了手势密码(跳到首页)
     */
    private void setLockPatternSuccess() {
        if (is_check) {
            UserInfoGlobal.setIsOpenGuesture(true);
            ToastUtil.makeText(this, "修改手势密码成功");
            finish();
        } else {
            UserInfoGlobal.setIsOpenGuesture(true);
            new SelectMenuTipsDilaog(this).setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
                @Override
                public void onLeft() {
                    finish();
                }

                @Override
                public void onRight() {

                }
            }).showOneSelectData("恭喜您", R.mipmap.dialog_tips_success, "手势密码设置成功，赶紧去借点钱花花吧！", "进入智信管家").show();


//            ToastUtil.makeText(this, "创建手势密码成功");
//            UserInfoGlobal.setIsOpenGuesture(true);
//            Util.startActivity(CreateGestureActivity.this, MainActivity.class);
//            finish();

        }

//        ToastUtil.makeText(this, "创建手势密码成功");
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        Dialog.showDefaultDialog(this, "", "设置手势密码可以方便登录也保障了您的账户安全，确定跳过吗？", "跳过", "继续设置", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {
                finish();
            }
        });
    }

    @OnClick(R.id.btn_wechat)
    public void onViewClicked1() {
        Util.startActivity(this, WechatChatActivity.class);
    }

    private enum Status {
        //默认的状态，刚开始的时候（初始化状态）
        DEFAULT(R.string.create_gesture_default, R.color.main_color),
        //第一次记录成功
        CORRECT(R.string.create_gesture_correct, R.color.main_color),
        //连接的点数小于4（二次确认的时候就不再提示连接的点数小于4，而是提示确认错误）
        LESSERROR(R.string.create_gesture_less_error, R.color.red_f4333c),
        //二次确认错误
        CONFIRMERROR(R.string.create_gesture_confirm_error, R.color.red_f4333c),
        //二次确认正确
        CONFIRMCORRECT(R.string.create_gesture_confirm_correct, R.color.main_color);

        private Status(int strId, int colorId) {
            this.strId = strId;
            this.colorId = colorId;
        }

        private int strId;
        private int colorId;
    }
}
